package net.dntuan.resttemplate;

import java.io.IOException;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

/**
 * Add Authorization header to every request
 *
 * @author tuan.dang
 *
 * $LastChangedRevision: 94 $ <br>
 * $LastChangedDate: 2014-04-29 10:18:50 +0000 (Tue, 29 Apr 2014) $
 */
public class TokenInterceptor implements ClientHttpRequestInterceptor {
  private String token;

  public TokenInterceptor() {
  }

  public TokenInterceptor(String givenToken) {
    this.token = givenToken;
  }

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
      throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add("Authorization", "Bearer " + token);
    return execution.execute(request, body);
  }

}
